<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2022/12/5
 * Time: 17:19
 */

declare (strict_types=1);

namespace app\middleware;

use think\Response;

class App
{
    private $controller = ['Login','Config'];//跳过验证的控制器
    private $action = [];//跳过验证的方法
    private $controller_action = [];
    /**
     * ApiAuth鉴权
     * @param \think\facade\Request $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle($request, \Closure $next): Response {
        if (strtoupper($request->method()) == "OPTIONS")
            throw new \think\exception\HttpResponseException(Response::create());
        $ApiAuth = $request->header('Api-Auth', '');
        $controller = str_replace('app.','',\think\facade\Request::controller());
        $action = \think\facade\Request::action();
        if(in_array($action,$this->action)) return $next($request);
        if(in_array($controller,$this->controller)) return $next($request);
        if(in_array($controller.'/'.$action,$this->controller_action))return $next($request);
        if (!empty($ApiAuth)) {
            $userInfo = cache('Login:app'.  $ApiAuth);
            if (empty($userInfo)) return json(['code' => 401, 'msg'  => 'ApiAuth不匹配', 'data' => []]);
            global $user;
            $user = \app\model\tb\TbUser::where('user_id',$userInfo->user_id)->find();
//            if($user->token->token != $ApiAuth) return json(['code' => 401, 'msg'  => '检测到其他地点登录', 'data' => []],401)->header($header);
//            $is_bool = ($user->key == 'admin' || $user->key == 'manager') || $user->key == 'financeOfWarehouse';
//            if (!$is_bool)
//                return json(['code' => 403,'msg' => '无权访问接口'],403);
            return $next($request);
        } else {
            return json(['code' => 401, 'msg'  => '缺少ApiAuth', 'data' => []],401);
        }
    }
}